package io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class NioSelectorServer {

    //只去遍历那些存在事件的socket

    public static void main(String[] args) throws IOException {
        //创建NIO ServerSocketChannel,与BIO得serverSocket类似
        ServerSocketChannel serverSocket = ServerSocketChannel.open();
        serverSocket.socket().bind(new InetSocketAddress(9000));
        //设置ServerSocketChannel为非阻塞
        serverSocket.configureBlocking(false);
        //打开Selector（多路复用器）处理Channel,即创建epoll
        Selector selector = Selector.open();
        //把ServerSocketChannel注册到selector上，并且selector监听客户端accept连接
        SelectionKey selectionKey = serverSocket.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服务启动成功");

        while (true) {
            //阻塞等待需要处理的事件发生
            selector.select();

            //获取selector中注册的全部事件 SelectionKey 实例
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();

            //遍历SelectionKey事件进行处理
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isAcceptable()) {
                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    //这里只注册了读事件，如果是需要给客户端发送消息可以注册写事件
                    SelectionKey sk = socketChannel.register(selector, SelectionKey.OP_ACCEPT);
                    System.out.println("客户端连接成功");
                } else if (key.isReadable()) {
                    //如果是OP_READ事件，则进行读取和打印
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                    //非阻塞模式read方法不会阻塞
                    int len = socketChannel.read(byteBuffer);
                    //如果有数据，把数据打印出来
                    if (len > 0)
                        System.out.println("接收到消息：" + new String(byteBuffer.array()));
                    else if (len == -1) {
                        //如果客户端断开，把socket从集合当中去掉
                        iterator.remove();
                        System.out.println("客户端断开连接");
                    }
                }
            }
        }
    }

}
